package com.hongmeng.teamwork.listener;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.hongmeng.teamwork.constants.StatusConstant;
import com.hongmeng.teamwork.convert.TeamworkProjectConvert;
import com.hongmeng.teamwork.convert.UserConvert;
import com.hongmeng.teamwork.domain.IGroupDomainService;
import com.hongmeng.teamwork.domain.IMessageDomainService;
import com.hongmeng.teamwork.entity.dto.*;
import com.hongmeng.teamwork.entity.event.ProjectMessageEvent;
import com.hongmeng.teamwork.entity.event.TaskMessageEvent;
import com.hongmeng.teamwork.entity.po.TeamworkProject;
import com.hongmeng.teamwork.entity.po.TeamworkTask;
import com.hongmeng.teamwork.entity.po.TeamworkTaskUserRel;
import com.hongmeng.teamwork.entity.po.User;
import com.hongmeng.teamwork.enums.TaskStatusEnum;
import com.hongmeng.teamwork.factory.task.TaskOptFactory;
import com.hongmeng.teamwork.service.ITeamworkProjectService;
import com.hongmeng.teamwork.service.ITeamworkTaskUserRelService;
import com.hongmeng.teamwork.tempalte.MessageSendTemplate;
import com.lark.oapi.service.im.v1.enums.CreateMessageReceiveIdTypeEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Log4j2
@Async("myThreadPoolExecutor")
@Component
public class MessageListener {

    @Resource
    private IMessageDomainService messageDomainService;
    @Resource
    private IGroupDomainService groupDomainService;
    @Resource
    private ITeamworkProjectService projectService;
    @Resource
    private ITeamworkTaskUserRelService taskUserRelService;
    @Resource
    private TaskOptFactory factory;

    @EventListener(classes = {ProjectMessageEvent.class})
    public void sendMsg(ProjectMessageEvent event) {
        // 创建项目群
        TeamworkProjectDto teamworkProjectDto = (TeamworkProjectDto) event.getSource();
        ProjectGroupRelDto projectGroupRelDto = TeamworkProjectConvert.INSTANCE.convertEntityToRelDto(event.getTeamworkProject(), teamworkProjectDto);
        User user = UserConvert.INSTANCE.convertDtoToEntity(teamworkProjectDto.getCreatedUser());
        projectGroupRelDto.setCreatedUser(user);
        String chatId = groupDomainService.createGroup(projectGroupRelDto);
        // 创建完项目之后通过机器人给创建人发送消息卡片告知项目创建完毕
        messageDomainService.sendMessage(MessageDto.builder()
                .content(MessageSendTemplate.createProjectTemplate(teamworkProjectDto.getCreatedUser().getName(),
                        teamworkProjectDto.getName(),
                        event.isSaveStatusFlag() ? StatusConstant.CREATE_PROJECT_SUCCESS : StatusConstant.CREATE_PROJECT_FAILURE))
                .accessToken(teamworkProjectDto.getAccessToken())
                .receiveIdType(CreateMessageReceiveIdTypeEnum.CHAT_ID)
                .receiveId(chatId)
                .build());
    }

    @EventListener(classes = {TaskMessageEvent.class})
    public void handleTaskOptMessage(TaskMessageEvent event) {
        TeamworkTask teamworkTask = event.getTeamworkTask();
        TeamworkTaskDto teamworkTaskDto = (TeamworkTaskDto) event.getSource();
        TeamworkProject teamworkProject = projectService.queryById(teamworkTask.getProjectId());
        TeamworkTaskUserRel taskUserRel = new TeamworkTaskUserRel();
        taskUserRel.setTaskId(teamworkTask.getId());
        String oldLeaderUser = new Gson().fromJson(taskUserRelService.queryByCondition(taskUserRel).get(0).getUserJson(), User.class).getName();

        // 构建消息
        String message = factory.buildMessage(new TaskMessageDto(teamworkTask, teamworkTaskDto, teamworkProject.getName(), oldLeaderUser), event.getOptType());

        // 给任务负责人发送消息
        messageDomainService.sendMessage(MessageDto.builder()
                .content(message)
                .accessToken(teamworkTaskDto.getAccessToken())
                .receiveIdType(CreateMessageReceiveIdTypeEnum.OPEN_ID)
                .receiveId(teamworkTaskDto.getLeadUser().getOpenId())
                .build());

        // 邀请任务负责人进群
        ProjectGroupRelDto projectGroupRelDto = new ProjectGroupRelDto();
        projectGroupRelDto.setProjectId(event.getTeamworkTask().getProjectId());
        projectGroupRelDto.setOpenIdList(Lists.newArrayList(teamworkTaskDto.getLeadUser().getOpenId()));
        String groupId = groupDomainService.popUserIntoGroup(projectGroupRelDto);

        // 给群发消息
        messageDomainService.sendMessage(MessageDto.builder()
                .content(message)
                .accessToken(teamworkTaskDto.getAccessToken())
                .receiveIdType(CreateMessageReceiveIdTypeEnum.CHAT_ID)
                .receiveId(groupId)
                .build());
    }
}
